package com.wwz.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wwz.constants.LocalToken;
import com.wwz.constants.LoginEnum;
import com.wwz.dao.UserDao;
import com.wwz.entity.User;
import com.wwz.entity.UserDetailsImpl;
import com.wwz.entity.UserEntity;
import com.wwz.feign.ProductFeign;
import com.wwz.service.UserService;
import com.wwz.tcc.TccUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao,User> implements UserService{
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TccUserService tccUserService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public int insert(String name){
       return tccUserService.insert(null,name,1L);
    }

    /**
     * 用户登录
     * @author:wwz
     * @param userEntity
     * @return
     */
    public LoginEnum login(UserEntity userEntity){
        String name = userEntity.getUsername();
        String password = userEntity.getPassword();
        Map<String,String> map = userDao.login(name,password);
        if(ObjectUtils.isEmpty(map)){
            return LoginEnum.PWD_OR_USER_IS_EMPTY;
        }
        String pwd = map.getOrDefault("password","").toString();
        if(!password.equals(pwd)){
            return LoginEnum.PWD_OR_USER_IS_EMPTY;
        }
        String uuid = UUID.randomUUID().toString();
        LocalToken.Token.set(uuid);
        UserDetails userDetails = new UserDetailsImpl(map);
        redisTemplate.opsForValue().set(uuid,userDetails,2L, TimeUnit.HOURS);
        return LoginEnum.OK;
    }

}

